import { addNotesRequest } from '@/apis/notes'
import { storeAll } from '@/store'
import { layout, tailLayout } from '@/utils/contants'
import { Button, DatePicker, Form, Select, message } from 'antd'
import { observer } from 'mobx-react-lite'
import React, { useEffect, useState } from 'react'

const { RangePicker } = DatePicker
const AddNotes: React.FC = () => {
	const [form] = Form.useForm()
	const [carOptions, setCarOptions] = useState<{ value: number, label: string }[]>([])
	const { carsStore: { cars }, notesStore: { notes, getNotes } } = storeAll

	useEffect(() => {
		const notesCid = notes.map(item => item.cid)
		const newCars = cars.filter(item => !notesCid.includes(item.id))
		const options = newCars.map(item => ({
			value: item.id,
			label: item.number
		}))
		setCarOptions(options)
	}, [cars, notes])

	const onFinish = (value: any) => {
		const searchTime = value.time
		if (searchTime && searchTime[0]) {
			value.inTime = searchTime[0].format('YYYY-MM-DD HH:mm:ss')
		}
		if (searchTime && searchTime[1]) {
			value.outTime = searchTime[1].format('YYYY-MM-DD HH:mm:ss')
		}
		addNotesRequest(value).then((res: any) => {
			message.success(res.message)
			form.resetFields()
			getNotes()
		})
	}

	return <div className="addNotesWrap">
		<Form {...layout} form={form} onFinish={onFinish}>
			<Form.Item label="车牌号" name="cid" rules={[{ required: true, message: '请输入车牌号' }]}>
				<Select options={carOptions}></Select>
			</Form.Item>
			<Form.Item label="出入时间" name="time" rules={[{ required: true, message: '请选择出入时间' }]}>
				<RangePicker allowEmpty={[false, true]} showTime></RangePicker>
			</Form.Item>
			<Form.Item {...tailLayout}>
				<Button type="primary" htmlType="submit">
					添加
				</Button>
				<Button htmlType="button" onClick={() => form.resetFields()}>
					重置
				</Button>
			</Form.Item>
		</Form>
	</div>
}

export default observer(AddNotes)